package com.dhcc.sdc.busi.function;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.busi.dao.*;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.*;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.core.framework.util.ObjectUtil;
import com.dhcc.core.framework.util.SpringContextHolder;
import com.dhcc.sdc.base.entity.ContraindicationEntity;
import com.dhcc.sdc.base.service.IContraindicationService;
import com.dhcc.sdc.busi.entity.SdcBusiContraindicationEntity;
import com.dhcc.sdc.busi.service.ISdcBusiContraindicationService;
import com.dhcc.sdc.busi.service.ISdcBusiEvaluationService;
import com.dhcc.sdc.cdss.dao.CdssApiMapper;
import com.dhcc.sds.base.dao.SdsFunctionMapper;
import com.dhcc.sds.busi.entity.SdsQcincaseDataEntity;
import com.dhcc.sds.busi.service.ISdsQcincaseDataService;
import com.dhcc.sds.busi.service.ISdsQcincaseService;
import com.dhcc.sds.standard.dao.SdsStandDicMapper;
import com.dhcc.sds.standard.dao.SdsStandDicsubMapper;
import com.dhcc.sds.standard.dao.SdsStandSourceMapper;
import com.dhcc.sds.standard.entity.SdsStandDicEntity;
import com.dhcc.sds.standard.entity.SdsStandDicsubEntity;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.util.NLPUtil;
import com.dhcc.sds.util.StrUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 质控项目取值函数类
 * @author:zhangdc
 * @date:2022年08月16日14:02:49
 * @Copyright: (c) DHCC All rights reserved.
 */
@Service("getSdcValueSrv")
public class GetSdcValueSrv {
    static SdsStandDicsubMapper sdsStandDicsubMapper = SpringContextHolder.getBean("sdsStandDicsubMapper");
    static SdsStandDicMapper sdsStandDicMapper = SpringContextHolder.getBean("sdsStandDicMapper");
    static SdsStandSourceMapper sdsStandSourceMapper = SpringContextHolder.getBean("sdsStandSourceMapper");
    static SdsFunctionMapper sdsFunctionMapper = SpringContextHolder.getBean("sdsFunctionMapper");
    static CdcEpisodeMapper cdcEpisodeMapper = SpringContextHolder.getBean("cdcEpisodeMapper");
    static CdcSurgeryMapper cdcSurgeryMapper = SpringContextHolder.getBean("cdcSurgeryMapper");
    static CdcDiagnosisMapper cdcDiagnosisMapper = SpringContextHolder.getBean("cdcDiagnosisMapper");
    static ICdcDictionaryService cdcDictionaryService = SpringContextHolder.getBean("cdcDictionaryService");
    static ICdcTransferService cdcTransferService = SpringContextHolder.getBean("cdcTransferService");
    static ICdcLocationService cdcLocationService = SpringContextHolder.getBean("cdcLocationService");
    static ICdcOrdexecService cdcOrdexecService = SpringContextHolder.getBean("cdcOrdexecService");
    static ICdcOrdmastService cdcOrdmastService = SpringContextHolder.getBean("cdcOrdmastService");
    static ISdcBusiEvaluationService sdcBusiEvaluationService = SpringContextHolder.getBean("sdcBusiEvaluationService");
    static ISdsQcincaseService sdsQcincaseService = SpringContextHolder.getBean("sdsQcincaseService");
    static ISdsQcincaseDataService sdsQcincaseDataService = SpringContextHolder.getBean("sdsQcincaseDataService");
    static IContraindicationService baseContraindicationService = SpringContextHolder.getBean("contraindicationService");
    static ISdcBusiContraindicationService sdcBusiContraindicationService = SpringContextHolder.getBean("sdcBusiContraindicationService");
    static IConfigurationService configurationService = SpringContextHolder.getBean("configurationService");
    @Autowired
    private ICdcDiagnosisService cdcDiagnosisService;
    @Autowired
    private ICdcLabVisitService labVisitService;
    @Autowired
    private CdssApiMapper cdssApiMapper;
    @Autowired
    CdcEmrMapper emrMapper;
    @Autowired
    CdcBsEmrStructMapper cdcBsEmrStructMapper;

    /**
     * 获取病人评估/评价信息
     * 通过数据源和取值字段
     *
     * @param episodeId  就诊号
     * @param param      参数
     * @param resultType 返回类型
     * @return 评估信息
     */
    public <T> T Assessment(Long episodeId, String param, String resultType) {
        switch (resultType) {
            case "Quantity":
                //数量
                Integer quantity = sdcBusiEvaluationService.selectAssessmentQuantity(episodeId, param);
                return (T) quantity;
            case "Grade":
                //等级
                String grade = sdcBusiEvaluationService.selectAssessmentGrade(episodeId, param);
                return (T) grade;
            case "Score":
                //分值
                Float score = sdcBusiEvaluationService.selectAssessmentScore(episodeId, param);
                return (T) score;
            case "Time":
                //时间
                //com.dhcc.core.framework.util.DateUtil.compareDate
                String dateTime = sdcBusiEvaluationService.selectAssessmentTime(episodeId, param);
                return (T) dateTime;
            case "EachGrade":
                //时间
                String levelStr = sdcBusiEvaluationService.selectAssessmentLevelStr(episodeId, param);
                return (T) levelStr;
            default:
                return (T) new String("");
        }
    }

    /**
     * 获取就诊信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object BaseInfoData(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        if (CommonUtil.isNotEmpty(resultType)) {
            switch (resultType) {
                case "OEDateT":
                    //到达本院急诊或者门诊日期时间
                    CdcEpisodeEntity cdcEpisodeEntity = cdcEpisodeMapper.selectById(episodeId);
                    if (!StringUtils.isEmpty(cdcEpisodeEntity)) {
                        //住院次数
                        Integer admNums = cdcEpisodeEntity.getAdmNums();
                        //患者主索引
                        String patientCode = cdcEpisodeEntity.getPatientCode();
                        if (!StringUtils.isEmpty(admNums) && (admNums > 1)) {
                            List<CdcEpisodeEntity> CdcEpisodeEntitys = cdcEpisodeMapper.selectByPatientCode(patientCode);
                            //就诊类型:E急诊
                            CdcDictionaryEntity admType1 = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_type", "E");
                            //就诊类型:O门诊
                            CdcDictionaryEntity admType2 = cdcDictionaryService.queryByTypeCodeAndCode("PatData", "bus_adm_type", "O");
                            for (CdcEpisodeEntity cdcEpisodeEntity1 : CdcEpisodeEntitys) {
                                //就诊类型过滤(只需要门诊和急诊的)
                                if (Objects.equals(admType1.getId(), cdcEpisodeEntity1.getBusAdmTypeId()) || Objects.equals(admType2.getId(), cdcEpisodeEntity1.getBusAdmTypeId())) {
                                    Long h = com.dhcc.sds.util.DateUtil.getDateCompare(cdcEpisodeEntity.getAdmDate(), cdcEpisodeEntity1.getAdmDate(), "h");
                                    if (h < 24) {
                                        resultVal = DateUtil.format(cdcEpisodeEntity1.getAdmDate(), "yyyy-MM-dd HH:mm:ss");
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    break;
                case "InCCUDateT":
                case "InICUDateT":
                    //入住CCU日期时间
                    Wrapper<CdcTransferEntity> transferInCCU = new EntityWrapper<>();
                    transferInCCU.eq("episode_id", episodeId).eq("is_active", 1);
                    List<CdcTransferEntity> cdcTransferInCCU = cdcTransferService.selectList(transferInCCU);
                    for (CdcTransferEntity cdcTransferEntity : cdcTransferInCCU) {
                        if (!StringUtils.isEmpty(cdcTransferEntity.getTranBedId())) {
                            //只检索转科记录
                            continue;
                        }
                        CdcLocationEntity locationEntity = cdcLocationService.selectById(cdcTransferEntity.getTranLocId());
                        if (!StringUtils.isEmpty(locationEntity)) {
                            if (locationEntity.getDescription().matches(".*ICU.*|.*监护.*|.*CCU.*")) {
                                resultVal = DateUtil.format(cdcTransferEntity.getTranDate(), "yyyy-MM-dd HH:mm:ss");
                                break;
                            }
                        }
                    }
                    break;
                case "OutCCUDateT":
                    //离开CCU日期时间
                    Wrapper<CdcTransferEntity> transferOutCCU = new EntityWrapper<>();
                    transferOutCCU.eq("episode_id", episodeId).eq("is_active", 1);
                    List<CdcTransferEntity> cdcTransferOutCCU = cdcTransferService.selectList(transferOutCCU);
                    for (CdcTransferEntity cdcTransferEntity : cdcTransferOutCCU) {
                        if (!StringUtils.isEmpty(cdcTransferEntity.getTranBedId())) {
                            //只检索转科记录
                            continue;
                        }
                        CdcLocationEntity locationEntity = cdcLocationService.selectById(cdcTransferEntity.getTranLocId());
                        if (!StringUtils.isEmpty(locationEntity)) {
                            if (locationEntity.getDescription().matches(".*ICU.*|.*监护.*|.*CCU.*")) {
                                resultVal = DateUtil.format(cdcTransferEntity.getFromDate(), "yyyy-MM-dd HH:mm:ss");
                                break;
                            }
                        }
                    }
                    break;
                case "InHosTrans":
                    //到院交通工具,默认私家车
                    resultVal = "私家车";
                    Wrapper<CdcOrdexecEntity> ordexecEntityWrapper = new EntityWrapper<>();
                    ordexecEntityWrapper.eq("episode_id", episodeId).eq("is_active", 1);
                    List<CdcOrdexecEntity> cdcOrdexecEntities = cdcOrdexecService.selectList(ordexecEntityWrapper);
                    for (CdcOrdexecEntity cdcOrdexecEntity : cdcOrdexecEntities) {
                        CdcOrdmastEntity ordmastEntity = cdcOrdmastService.selectById(cdcOrdexecEntity.getOrderMastId());
                        if (!StringUtils.isEmpty(ordmastEntity)) {
                            if (ordmastEntity.getDescription().contains("救护车")) {
                                resultVal = "救护车";
                                break;
                            }
                        }
                    }
                    break;
                default:
                    // 通过就诊号获取患者就诊信息
                    Map<String, Object> episodeInfo = sdsFunctionMapper.getPatientInfo(episodeId);
                    // 获取对象值
                    resultVal = ObjectUtil.toString(episodeInfo.get(resultType));
                    if (CommonUtil.equals(resultVal, "男")) {
                        resultVal = "M";
                    } else if (CommonUtil.equals(resultVal, "女")) {
                        resultVal = "F";
                    }
                    break;
            }
        }
        return resultVal;
    }

    /**
     * 获取诊断信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object DiagInfo(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        Map param = new HashMap();
        param.put("episodeId", episodeId);
        if (CommonUtil.isNotEmpty(paramStr)) {
            paramStr.replace("，", ",");
            String[] paramArr = paramStr.split(",");
            param.put("diagKeys", paramArr);
        }
        // 获取患者诊断数据
        List<CdcDiagnosisEntity> diagnosisList = cdcDiagnosisMapper.selectDiagInfo(param);

        if (CommonUtil.isEmpty(resultType) || "Quantity".equals(resultType)) {
            // 输出类型为空，则默认返回数量
            resultVal = diagnosisList.size();
        } else {
            String resultStr = "";
            for (CdcDiagnosisEntity cdcDiagnosisEntity : diagnosisList) {
                String icd10 = cdcDiagnosisEntity.getIcd10();
                if (Objects.equals("M4DICD10", resultType)) {
                    //主要诊断ICD-10四位亚目编码与名称
                    if (icd10.length() > 4) {
                        resultStr = icd10.substring(0, 5);
                    }
                    String lastChar = resultStr.substring(resultStr.length() - 1);
                    if ("x".equals(lastChar)) {
                        resultStr = resultStr.substring(0, resultStr.length() - 1);
                    }
                    lastChar = resultStr.substring(resultStr.length() - 1);
                    if (".".equals(lastChar)) {
                        resultStr = resultStr.substring(0, resultStr.length() - 1);
                    }
                } else if (Objects.equals("M6DICD10", resultType)) {
                    //主要诊断ICD-10六位临床扩展编码与名称
                    String substring = "";
                    if (icd10.length() >= 8) {
                        substring = icd10.substring(7, 8);
                    }
                    if (Objects.equals("x", substring) && icd10.length() >= 11) {
                        resultStr = icd10.substring(0, 11);
                    } else if (!Objects.equals("x", substring) && icd10.length() >= 7) {
                        resultStr = icd10.substring(0, 7);
                    }
                } else if (Objects.equals("DiagDate", resultType)) {
                    // 诊断时间
                    Date diagDate = cdcDiagnosisEntity.getDiagDate();
                    if (CommonUtil.isEmpty(diagDate)) continue;
                    resultVal = DateUtil.getTime(diagDate);
                }
                if (!StringUtils.isEmpty(resultStr)) {
                    resultVal = resultStr;
                    break;
                }
            }
        }

        return resultVal;
    }

    /**
     * 获取医嘱信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object OrderInfoData(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        List<Long> ordMastList = new ArrayList<>();
        if (CommonUtil.isNotEmpty(paramStr)) {
            if (!paramStr.equals("抗菌药物")) {

                paramStr = paramStr.replace("，", ",");
                String[] paramArr = paramStr.split(",");

                Wrapper<SdsStandDicsubEntity> wpr = new EntityWrapper<>();
                Map<String, String> sqlStrMap = this.handleRegexp(paramArr,"dic_desc");
                String includeStr = sqlStrMap.get("keywordOrTxt");
                String filterStr = sqlStrMap.get("filterTxt");
                wpr.where("1=1");
                if (CommonUtil.isNotEmpty(includeStr)) {
                    wpr.andNew(includeStr);
                }
                if (CommonUtil.isNotEmpty(filterStr)) {
                    wpr.andNew("dic_desc not regexp {0}",filterStr);
                }
                //如果参数不为空，通过标准化子项目查找关联医嘱项
                List<SdsStandDicsubEntity> dicSubList = sdsStandDicsubMapper.selectList(wpr);
                Map map = new HashMap();
                List<Long> subOrdMastList = new ArrayList<>();
                if (!dicSubList.isEmpty()) {
                    for (SdsStandDicsubEntity dicsubEntity : dicSubList) {
                        // 查询标准子项所有关联医嘱
                        map.put("dicSubId", dicsubEntity.getId());
                        subOrdMastList = sdsFunctionMapper.getOrdMast(map);
                        ordMastList.addAll(subOrdMastList);
                    }
                } else {
                    // 子项匹配不到，匹配标准项
                    Wrapper<SdsStandDicEntity> dicWpr = new EntityWrapper<>();
                    sqlStrMap = this.handleRegexp(paramArr,"dic_cat_desc");
                    includeStr = sqlStrMap.get("keywordOrTxt");
                    filterStr = sqlStrMap.get("filterTxt");
                    wpr.where("1=1");
                    if (CommonUtil.isNotEmpty(includeStr)) {
                        dicWpr.andNew(includeStr);
                    }
                    if (CommonUtil.isNotEmpty(filterStr)) {
                        dicWpr.andNew("dic_cat_desc not regexp {0}",filterStr);
                    }
                    List<SdsStandDicEntity> dicList = sdsStandDicMapper.selectList(dicWpr);
                    if (!dicList.isEmpty()) {
                        for (SdsStandDicEntity dicEntity : dicList) {
                            map.clear();
                            // 查询标准项所有关联医嘱
                            map.put("dicId", dicEntity.getId());
                            subOrdMastList = sdsFunctionMapper.getOrdMast(map);
                            if (subOrdMastList.isEmpty()) {
                                //标准项未配置对照医嘱，取标准子项配置
                                subOrdMastList = sdsFunctionMapper.getOrdMastByDicId(dicEntity.getId());
                            }
                            ordMastList.addAll(subOrdMastList);
                        }
                    }
                }
                if (ordMastList.isEmpty()) {
                    // 如果标准项和子项未找到关联医嘱，直接模糊匹配医嘱项
                    sqlStrMap = this.handleRegexp(paramArr,"description");
                    includeStr = sqlStrMap.get("keywordOrTxt");
                    filterStr = sqlStrMap.get("filterTxt");
                    ordMastList.addAll(sdsFunctionMapper.getOrdMastByKeyword(includeStr, filterStr));
                }
            } else {
                // 如果参数是“抗菌药物”，然后获取数据源下所有子项的关联医嘱
                List<SdsStandSourceEntity> sourceLst = sdsStandSourceMapper.selectList(
                        new EntityWrapper<SdsStandSourceEntity>().eq("source_desc", paramStr).eq("is_active", 1));
                if (!sourceLst.isEmpty()) {
                    SdsStandSourceEntity sourceEntity = sourceLst.get(0);
                    List<SdsStandDicEntity> dicList = sdsStandDicMapper.selectList(
                            new EntityWrapper<SdsStandDicEntity>().eq("source_id", sourceEntity.getId()));
                    List<Long> subOrdMastList = new ArrayList<>();
                    for (SdsStandDicEntity dic : dicList) {
                        // 获取所有子项
                        List<SdsStandDicsubEntity> dicSubList = sdsStandDicsubMapper.selectList(new EntityWrapper<SdsStandDicsubEntity>().eq("dic_id", dic.getId()));
                        for (SdsStandDicsubEntity dicsubEntity : dicSubList) {
                            // 查询标准子项所有关联医嘱
                            Map map = new HashMap();
                            map.put("dicSubId", dicsubEntity.getId());
                            subOrdMastList = sdsFunctionMapper.getOrdMast(map);
                            ordMastList.addAll(subOrdMastList);
                        }
                    }
                }
            }
        }
        if (ordMastList.isEmpty()) {
            return resultVal;
        }
        // 去重
        ordMastList = ordMastList.stream().distinct().collect(Collectors.toList());
        List<Map<String, Object>> list = new ArrayList<>();
        if ("OutHosQuantity".equals(resultType)){
            CdcDictionaryEntity cdcDictionaryEntity = cdcDictionaryService.queryByTypeCodeAndCode("OrdData", "bus_order_priority", "OUT");
            //出院带药-数量
            list = sdsFunctionMapper.selectOutOrdExec(episodeId, null, ordMastList, cdcDictionaryEntity.getId());
        }else {
            // 获取患者所有医嘱信息, 默认按照医嘱开始日期排序
            list = sdsFunctionMapper.selectOrdExec(episodeId, null, ordMastList, "ORDER BY oe.start_date");
        }

        if (CommonUtil.isEmpty(resultType) || "Quantity".equals(resultType) || "OutHosQuantity".equals(resultType)) {
            // 输出类型为空，则默认返回数量
            resultVal = list.size();
        } else {
            for (Map<String, Object> map : list) {
                if (CommonUtil.isNotEmpty(map.get(resultType))) {
                    resultVal = map.get(resultType);
                    break;
                }
            }
        }

        return resultVal;
    }

    /**
     * 获取生命体征信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object NurInfo(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        Map param = new HashMap<>();
        param.put("episodeId", episodeId);
        // 如果输出字段不为空，直接返回
        if (CommonUtil.isNotEmpty(resultType)) {
            param.put("signCode", resultType);
            resultVal = sdsFunctionMapper.getSignByCode(param);
        } else if (CommonUtil.isNotEmpty(paramStr)) {
            // 如果输出字段为空，则根据参数模糊匹配体征项取值
            param.put("signDesc", paramStr);
            resultVal = sdsFunctionMapper.getSignByCode(param);
        }
        if (resultVal == null) {
            resultVal = "";
        }
        return resultVal;
    }

    /**
     * 获取手术信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object OperInfo(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        //查询患者所有手术信息
        Wrapper<CdcSurgeryEntity> operWpr = new EntityWrapper<>();
        operWpr.eq("episode_id", episodeId);
        if (CommonUtil.isNotEmpty(paramStr)) {
            paramStr = paramStr.replace("，", ",");
            String[] paramArr = paramStr.split(",");

            Map<String, String> sqlStrMap = this.handleRegexp(paramArr,"description");
            String includeStr = sqlStrMap.get("keywordOrTxt");
            String filterStr = sqlStrMap.get("filterTxt");

            if (CommonUtil.isNotEmpty(includeStr)) {
                operWpr.andNew(includeStr);
            }
            if (CommonUtil.isNotEmpty(filterStr)) {
                operWpr.andNew("description not regexp {0}",filterStr);
            }
        }
        List<CdcSurgeryEntity> surgeryEntities = cdcSurgeryMapper.selectList(operWpr);
        if (CommonUtil.isNotEmpty(resultType)) {
            if (surgeryEntities.size() > 0) {
                CdcSurgeryEntity cdcSurgeryEntity = surgeryEntities.get(0);
                String code = cdcSurgeryEntity.getCode();
                if (Objects.equals("M4OCM3", resultType)) {
                    //主要手术操作栏中提取ICD-9-CM-3四位亚目编码与名称
                    if (code.length() > 4) {
                        code = code.substring(0, 5);
                    }
                    String lastChar = code.substring(code.length() - 1);
                    if ("x".equals(lastChar)) {
                        code = code.substring(0, code.length() - 1);
                    }
                    lastChar = code.substring(code.length() - 1);
                    if (".".equals(lastChar)) {
                        code = code.substring(0, code.length() - 1);
                    }
                    resultVal = code;
                } else if (Objects.equals("M6OCM3", resultType)) {
                    //主要手术操作栏中提取ICD-9-CM-3六位临床扩展编码与名称
                    String substring = "";
                    if (code.length() >= 8) {
                        substring = code.substring(7, 8);
                    }
                    if (Objects.equals("x", substring) && code.length() >= 11) {
                        resultVal = code.substring(0, 11);
                    } else if (code.length() >= 7) {
                        resultVal = code.substring(0, 7);
                    }
                } else if (CommonUtil.equals("startDate", resultType)) {
                    resultVal = DateUtil.getTime(cdcSurgeryEntity.getStartDate());
                } else if (CommonUtil.equals("endDate", resultType)) {
                    resultVal = DateUtil.getTime(cdcSurgeryEntity.getEndDate());
                }
            }
        } else {
            resultVal = surgeryEntities.size();
        }
        return resultVal;
    }

    /**
     * 获取护理记录信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object NursingMeasures(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        return resultVal;
    }

    /**
     * 获取检验信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object LisInfoData(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        List<Long> laborderIds = new ArrayList<>();
        if (CommonUtil.isNotEmpty(paramStr)) {
            paramStr = paramStr.replace("，", ",");
            //如果参数不为空，通过描述匹配标准化项目查找关联医嘱项
            String[] paramArr = paramStr.split(",");
            Wrapper<SdsStandDicEntity> dicWpr = new EntityWrapper<>();
            Map<String, String> sqlStrMap = this.handleRegexp(paramArr,"dic_cat_desc");
            String includeStr = sqlStrMap.get("keywordOrTxt");
            String filterStr = sqlStrMap.get("filterTxt");
            dicWpr.where("1=1");
            if (CommonUtil.isNotEmpty(includeStr)) {
                dicWpr.andNew(includeStr);
            }
            if (CommonUtil.isNotEmpty(filterStr)) {
                dicWpr.andNew("dic_cat_desc not regexp {0}",filterStr);
            }
            List<SdsStandDicEntity> dicList = sdsStandDicMapper.selectList(dicWpr);
            if (!dicList.isEmpty()) {
                Map map = new HashMap();
                for (SdsStandDicEntity dicEntity : dicList) {
                    // 查询标准项所有关联医嘱
                    map.put("dicId", dicEntity.getId());
                    //检验医嘱id
                    laborderIds.addAll(sdsFunctionMapper.getLisLinkOrdMthId(map));
                }
            }
            if (laborderIds.isEmpty()) {
                // 如果标准项未找到关联医嘱，直接模糊匹配检验医嘱项
                sqlStrMap = this.handleRegexp(paramArr,"description");
                includeStr = sqlStrMap.get("keywordOrTxt");
                filterStr = sqlStrMap.get("filterTxt");
                laborderIds.addAll(sdsFunctionMapper.getLabOrdByKeyword(includeStr,filterStr));
            }
        }

        if (laborderIds.isEmpty()) {
            return resultVal;
        }
        // 去重
        laborderIds = laborderIds.stream().distinct().collect(Collectors.toList());

        List<Map<String, Object>> list = sdsFunctionMapper.selectLabReport(episodeId, null, laborderIds, null);

        if (CommonUtil.isEmpty(resultType) || "LabCollNum".equals(resultType)) {
            // 输出类型为空，则默认返回数量
            resultVal = list.size();
        } else if ("LabCollFirstTime".equals(resultType)) {
            // 首次送检时间
            list = list.stream().sorted(Comparator.comparing(map -> map.get("LabCollDate").toString())).collect(Collectors.toList());
            for (Map<String, Object> map : list) {
                if (CommonUtil.isNotEmpty(map.get("LabCollDate"))) {
                    resultVal = map.get("LabCollDate");
                    break;
                }
            }
        }else if ("firstReportDate".equals(resultType)){
            // 首次报告日期
            list = list.stream().sorted(Comparator.comparing(map -> map.get("reportDate").toString())).collect(Collectors.toList());
            for (Map<String, Object> map : list){
                if (CommonUtil.isNotEmpty(map.get("reportDate"))){
                    resultVal = map.get("reportDate");
                    break;
                }
            }
        } else {
            for (Map<String, Object> map : list) {
                if (CommonUtil.isNotEmpty(map.get(resultType))) {
                    resultVal = map.get(resultType);
                    break;
                }
            }
        }

        return resultVal;
    }

    public Object LisInfo(Long episodeId, String paramStr, String resultType){
        return this.LisInfoData(episodeId, paramStr, resultType);
    }

    /**
     * 获取检验项目信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object LisItemInfoData(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        List<Long> labitemIds = new ArrayList<>();
        if (CommonUtil.isNotEmpty(paramStr)) {
            paramStr = paramStr.replace("，", ",");
            String[] paramArr = paramStr.split(",");
            Wrapper<SdsStandDicsubEntity> wpr = new EntityWrapper<>();
            Map<String, String> sqlStrMap = this.handleRegexp(paramArr,"dic_desc");
            String includeStr = sqlStrMap.get("keywordOrTxt");
            String filterStr = sqlStrMap.get("filterTxt");
            wpr.where("1=1");
            if (CommonUtil.isNotEmpty(includeStr)) {
                wpr.andNew(includeStr);
            }
            if (CommonUtil.isNotEmpty(filterStr)) {
                wpr.andNew("dic_desc not regexp {0}",filterStr);
            }
            //如果参数不为空，通过描述匹配标准化子项目查找关联检验项目代码
            List<SdsStandDicsubEntity> dicSubList = sdsStandDicsubMapper.selectList(wpr);
            if (!dicSubList.isEmpty()) {
                Map param = new HashMap();
                for (SdsStandDicsubEntity dicsubEntity : dicSubList) {
                    // 查询子项关联的检验项目
                    param.put("dicSubId", dicsubEntity.getId());
                    labitemIds.addAll(sdsFunctionMapper.getLisLinkExamId(param));
                }
            }
            if (labitemIds.isEmpty()) {
                sqlStrMap = this.handleRegexp(paramArr,"description");
                includeStr = sqlStrMap.get("keywordOrTxt");
                filterStr = sqlStrMap.get("filterTxt");
                labitemIds.addAll(sdsFunctionMapper.getLabItemByKeyword(includeStr,filterStr));
            }
        }
        if (labitemIds.isEmpty()) {
            return resultVal;
        }
        // 去重
        labitemIds = labitemIds.stream().distinct().collect(Collectors.toList());
        List<Map<String, Object>> labReportList = sdsFunctionMapper.getLabReportList(episodeId, null, labitemIds, null);

        if (CommonUtil.isEmpty(resultType) || "Quantity".equals(resultType)) {
            // 输出类型为空，则默认返回数量
            resultVal = labReportList.size();
        } else {
            for (Map<String, Object> map : labReportList) {
                if (CommonUtil.isNotEmpty(map.get(resultType))) {
                    resultVal = map.get(resultType);
                    break;
                }
            }
        }

        return resultVal;
    }

    /**
     * 获取检查报告信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object RisInfoData(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        List<Long> ordMastList = new ArrayList<>();
        if (CommonUtil.isNotEmpty(paramStr)) {
            paramStr = paramStr.replace("，", ",");
            //如果参数不为空，通过描述匹配标准化项目查找关联医嘱项
            String[] paramArr = paramStr.split(",");
            Wrapper<SdsStandDicEntity> dicWpr = new EntityWrapper<>();
            Wrapper<SdsStandDicsubEntity> wpr = new EntityWrapper<>();
            Map<String, String> sqlStrMap = this.handleRegexp(paramArr,"dic_desc");
            String includeStr = sqlStrMap.get("keywordOrTxt");
            String filterStr = sqlStrMap.get("filterTxt");
            wpr.where("1=1");
            if (CommonUtil.isNotEmpty(includeStr)) {
                wpr.andNew(includeStr);
            }
            if (CommonUtil.isNotEmpty(filterStr)) {
                wpr.andNew("dic_desc not regexp {0}",filterStr);
            }
            List<SdsStandDicEntity> dicList = sdsStandDicMapper.selectList(dicWpr);
            if (!dicList.isEmpty()) {
                Map map = new HashMap();
                for (SdsStandDicEntity dicEntity : dicList) {
                    // 查询标准项所有关联医嘱
                    map.put("dicId", dicEntity.getId());
                    //检查医嘱id
                    ordMastList.addAll(sdsFunctionMapper.getRisLinkOrdMthId(map));
                }
            }
            if (ordMastList.isEmpty()) {
                // 如果标准项和子项未找到关联医嘱，直接模糊匹配医嘱项
                sqlStrMap = this.handleRegexp(paramArr,"description");
                includeStr = sqlStrMap.get("keywordOrTxt");
                filterStr = sqlStrMap.get("filterTxt");
                ordMastList.addAll(sdsFunctionMapper.getOrdMastByKeyword(includeStr, filterStr));
            }
        }

        if (ordMastList.isEmpty()) {
            return resultVal;
        }
        // 去重
        ordMastList = ordMastList.stream().distinct().collect(Collectors.toList());
        List<Map<String, Object>> list = sdsFunctionMapper.selectExaminate(episodeId, null, ordMastList, null);

        String content = "";
        // 获取语义分析服务器地址地址
        if (CommonUtil.isEmpty(resultType) || "Quantity".equals(resultType)) {
            // 输出类型为空，则默认返回数量
            resultVal = list.size();
        }else if ("RepResult".equals(resultType) || "examDesc".equals(resultType)){
            //检查所见-输出
            for (Map<String, Object> map : list){
                if (CommonUtil.isNotEmpty(map.get(resultType))){
                    content = map.get(resultType) + "。";
                }
            }
            String nlpUrl = CdcConfigCache.me().getValueByKey("SDS", "SDAnalysisServer");
            resultVal = NLPUtil.parse(nlpUrl, content);

        } else {
            for (Map<String, Object> map : list) {
                if (CommonUtil.isNotEmpty(map.get(resultType))) {
                    resultVal = map.get(resultType);
                    break;
                }
            }
        }

        return resultVal;
    }

    public Object RisInfo (Long episodeId, String paramStr, String resultType) {
        return this.RisInfoData(episodeId, paramStr, resultType);
    }

    /**
     * 获取检查项目信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object RisItemInfoData(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        return resultVal;
    }

    /**
     * 获取检查结果信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object RisInfoData2(Long episodeId, String paramStr, String resultType){
        Object resultVal = "";
        List<Long> ordMastList = new ArrayList<>();
        if (CommonUtil.isNotEmpty(paramStr)){
            String nlpUrl = CdcConfigCache.me().getValueByKey("SDS", "SDAnalysisServer");
            if (paramStr.contains("#")){
                //处理检查结果-有无、检查结果-数值、检查结果-时间
                String[] split = paramStr.split("#");
                String paramStr1 = split[0];
                String keyWord = "";
                String paramStr2 = "";
                if (split[1].contains(",")){
                    keyWord = split[1].substring(0, split[1].indexOf(","));
                    paramStr2 = split[1].substring(split[1].indexOf(",") + 1, split[1].length());
                }else {
                    keyWord = split[1];
                }

                //处理检查结果-有无
                if(resultType.equals("haveCheckResult")){
                    List<Long> ordMastList1 = handleRisInfo(paramStr1);
                    if (!ordMastList1.isEmpty()){
                        ordMastList1 = ordMastList1.stream().distinct().collect(Collectors.toList());
                        List<Map<String, Object>> list1 = sdsFunctionMapper.selectExaminate(episodeId, null, ordMastList1, null);
                        //语义分析
                        String content = "";
                        for (Map<String, Object> map : list1){
                            if (CommonUtil.isNotEmpty(map.get("examDesc"))){
                                content += map.get("examDesc") + "。";
                            }
                            if (CommonUtil.isNotEmpty(map.get("resultDesc"))){
                                content += map.get("resultDesc") + "。";
                            }
                        }
                        String NLPValue = (String) NLPUtil.parse(nlpUrl, content);
                        String NLPRisValue = (String) NLPUtil.handleData(NLPValue, "ris");
                        if (!StringUtils.isEmpty(NLPRisValue)){
                            if (NLPRisValue.contains(keyWord)){
                                resultVal = true;
                                return resultVal;
                            }
                        }
                    }

                    if (!StringUtils.isEmpty(paramStr2)){
                        List<Long> ordMastList2 = handleRisInfo(paramStr2);
                        if (!ordMastList2.isEmpty()){
                            ordMastList2 = ordMastList2.stream().distinct().collect(Collectors.toList());
                            List<Map<String, Object>> list2 = sdsFunctionMapper.selectExaminate(episodeId, null, ordMastList2, null);
                            for (Map<String, Object> map : list2){
                                if (resultType.equals("haveCheckResult")){
                                    if (CommonUtil.isNotEmpty(map.get("examDesc"))){
                                        resultVal = true;
                                        return resultVal;
                                    }
                                    if (CommonUtil.isNotEmpty(map.get("resultDesc"))){
                                        resultVal = true;
                                        return resultVal;
                                    }
                                }
                            }
                        }
                    }
                }

                //TODO 检查结果-数值
                if(resultType.equals("checkResultTime")){

                }

                //检查结果-时间
                if (resultType.equals("checkResultTime")) {
                    paramStr1.replace("，", ",");
                    String[] paramStr1Arr = paramStr1.split(",");
                    for (String s1 : paramStr1Arr) {
                        List<Long> ordMastList1 = handleRisInfo(s1);
                        if (!ordMastList1.isEmpty()) {
                            ordMastList1 = ordMastList1.stream().distinct().collect(Collectors.toList());
                            List<Map<String, Object>> list1 = sdsFunctionMapper.selectExaminate(episodeId, null, ordMastList1, null);
                            //语义分析
                            for (Map<String, Object> map : list1) {
                                String content = "";
                                if (CommonUtil.isNotEmpty(map.get("repDate"))) {
                                    if (CommonUtil.isNotEmpty(map.get("examDesc"))) {
                                        content += map.get("examDesc") + "。";
                                    }
                                    if (CommonUtil.isNotEmpty(map.get("resultDesc"))) {
                                        content += map.get("resultDesc") + "。";
                                    }
                                    String NLPValue = (String) NLPUtil.parse(nlpUrl, content);
                                    String NLPRisValue = (String) NLPUtil.handleData(NLPValue, "ris");
                                    if (!StringUtils.isEmpty(NLPRisValue)) {
                                        if (NLPRisValue.contains(keyWord)) {
                                            resultVal = map.get("repDate");
                                            return resultVal;
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }else {
                //处理是否实施某项检查
                ordMastList = handleRisInfo(paramStr);
                ordMastList = ordMastList.stream().distinct().collect(Collectors.toList());
                List<Map<String, Object>> list = sdsFunctionMapper.selectExaminate(episodeId, null, ordMastList, null);
                if (resultType.equals("isImplCheck")){
                    if (!list.isEmpty()){
                        resultVal = true;
                        return resultVal;
                    }
                }
                //处理首次检查时间
                if (resultType.equals("firstCheckTime")){
                    for (Map<String, Object> map : list){
                        if (CommonUtil.isNotEmpty(map.get("orderDateT"))) {
                            resultVal = map.get("orderDateT");
                            return resultVal;
                        }
                    }
                }


            }
        }
        return resultVal;
    }

    /**
     * 获取常用信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object UsefulExpressions(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        if ("curTime".equals(resultType)) {
            resultVal = DateUtil.getTime();
        }else if ("AverageHospDays".equals(resultType)){
            resultVal = AverageHospDays(episodeId, paramStr, resultType);
        }else if ("MedianHospDays".equals(resultType)){
            resultVal = MedianHospDays(episodeId, paramStr, resultType);
        }else if ("AverageHospCost".equals(resultType)){
            resultVal = AverageHospCost(episodeId, paramStr, resultType);
        }else if ("MedianHospCost".equals(resultType)){
            resultVal = MedianHospCost(episodeId, paramStr, resultType);
        }else if ("PercentileHospDays".equals(resultType)){
            resultVal = PercentileHospDays(episodeId, paramStr, resultType);
        }else if ("PercentileHospCost".equals(resultType)){
            resultVal = PercentileHospCost(episodeId, paramStr, resultType);
        }
        return resultVal;
    }

    /**
     * 获取评价信息
     *
     * @param episodeId
     * @param paramStr
     * @param resultType
     * @return
     */
    public Object Evaluate(Long episodeId, String paramStr, String resultType) {
        Object resultVal = "";
        return resultVal;
    }
    /**
     * 诊断信息-诊断时间
     * 通过数据源和取值字段(这里配的是诊断类型)
     */
    public String diagTime(Long episodeId, String param) {
        CdcDiagnosisEntity cdcDiagnosisEntity = null;
        String time = "";
        if (!StringUtils.isEmpty(param)) {

            Wrapper<CdcDiagnosisEntity> wrapper = new EntityWrapper<>();
            wrapper.eq("episode_id", episodeId).like("description", param);
            cdcDiagnosisEntity = cdcDiagnosisService.selectOne(wrapper);
            Date diagDate = cdcDiagnosisEntity.getDiagDate();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time = sdf.format(diagDate);

        }
        return time;
    }

    /**
     * 电子病历-症状体征
     * 通过数据源和取值字段(这里配的是诊断类型)
     */
    public Object EmrInfo(Long episodeId, String params, String dataType) {
        boolean res = false;
        String[] items = params.split(",");
        Wrapper<CdcBsEmrStructEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("episode_id", episodeId).andNew()
                .eq("emr_title", "入院记录")
                .or().eq("emr_title", "日常病程记录")
                .or().eq("emr_title", "首次病程记录");
        List<CdcBsEmrStructEntity> cdcBsEmrStructEntities = cdcBsEmrStructMapper.selectList(wrapper);
        for (CdcBsEmrStructEntity emrEntity : cdcBsEmrStructEntities) {
            String emrNLPResult = emrEntity.getEmrNlpResult();
            if (CommonUtil.isNotEmpty(emrNLPResult)) {
                for (String item : items) {
                    if (emrNLPResult.contains(item)) {
                        res = true;
                        break;
                    }
                }
            }
        }
        return res;
    }

    public Object emrSymptoms(Long episodeId, String params) {
        boolean res = false;
        String[] items = params.split(",");
        Wrapper<CdcEmrEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("episode_id", episodeId).eq("title", "入院记录")
                .orNew()
                .eq("episode_id", episodeId).eq("title", "日常病程记录");


        List<CdcEmrEntity> cdcEmrEntities = emrMapper.selectList(wrapper);

        for (CdcEmrEntity emrEntity : cdcEmrEntities) {
            List<String> symAndSign = parse(emrEntity.getContent(), emrEntity.getTitle());
            if (symAndSign.containsAll(Arrays.asList(items))) {
                res = true;
                break;
            }
        }
        return res;
    }

    //nlp解析电子病例的内容
    public List<String> parse(String content, String title) {

        //String url = "http://111.205.6.207:1223/tag";
        List<String> symAndSign = new ArrayList<>();
        try {
            String nlpUrl = CdcConfigCache.me().getValueByKey("SDS", "SDAnalysisServer");
            JSONObject jsonparam = new JSONObject();
            jsonparam.put("data", content);
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(nlpUrl);
            StringEntity stringEntity = new StringEntity(jsonparam.toString(), "UTF-8");
            stringEntity.setContentType(new BasicHeader("Content-Type", "application/json;charset=utf-8 "));
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity, "UTF-8");
            System.out.println("res:" + res);

            JSONArray jsonArray = JSONArray.parseArray(res);
            System.out.println("jsonArray:" + jsonArray);

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String type = jsonObject.getString("type");
                String symptom = "";//症状
                String sign = "";

                //症状
                if (type.matches(".*symptom.*")) {
                    symptom = (String) jsonObject.get("name");
                    symAndSign.remove(symptom);
                    symAndSign.add(symptom);
                }
                //体征
                if (type.equals(".*sign.*")) {
                    sign = (String) jsonObject.get("name");
                    symAndSign.remove(sign);
                    symAndSign.add(sign);
                }
            }

            System.out.println("症状体征:" + symAndSign);

            client.close();
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return symAndSign;

    }


    /**
     * 送检报告-数量
     * 通过数据源和取值字段(这里配的是诊断类型)
     */
    public Integer labVisitNum(Long episodeId, String param) {
        List<CdcLabVisitEntity> cdcLabVisitEntities = new ArrayList<>();
        if (!StringUtils.isEmpty(param)) {
            String[] items = param.split(",");
            Wrapper<CdcLabVisitEntity> wrapper = new EntityWrapper<>();
            for (int i = 0; i < items.length; i++) {
                if (i == 0) {
                    wrapper.eq("episode_id", episodeId).like("specimen", items[i]);
                } else {
                    wrapper.orNew().eq("episode_id", episodeId).like("specimen", items[i]);
                }
            }
            cdcLabVisitEntities = labVisitService.selectList(wrapper);
        }

        return cdcLabVisitEntities.size();
    }


    /**
     * 送检报告-首次采集时间
     * 通过数据源和取值字段(这里配的是诊断类型)
     */
    public String labVisitTime(Long episodeId, String param) {

        List<CdcLabVisitEntity> cdcLabVisitEntities = new ArrayList<>();
        Date colDate = null;
        String time = "";
        if (!StringUtils.isEmpty(param)) {
            String[] items = param.split(",");
            Wrapper<CdcLabVisitEntity> wrapper = new EntityWrapper<>();
            for (int i = 0; i < items.length; i++) {
                if (i == 0) {
                    wrapper.eq("episode_id", episodeId).like("specimen", items[i]);
                } else {
                    wrapper.orNew().eq("episode_id", episodeId).like("specimen", items[i]);
                }
            }
            wrapper.orderBy("col_date", true);
            cdcLabVisitEntities = labVisitService.selectList(wrapper);
            if (cdcLabVisitEntities.size() > 0) {

                colDate = cdcLabVisitEntities.get(0).getColDate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                time = sdf.format(colDate);

            }
        }
        return time;
    }


    /**
     * 就诊信息-入住ICU时间
     */
    public String epiICUTime(Long episodeId){
        String directTime="";
        String transTime="";

        //直接进入ICU
        Wrapper<CdcEpisodeEntity> episodeWrapper = new EntityWrapper<>();
        episodeWrapper.eq("id", episodeId).eq("is_active", 1).orderBy("adm_date",true);
        List<CdcEpisodeEntity> cdcEpisodeList = cdcEpisodeMapper.selectList(episodeWrapper);
        for (int i = 0; i < cdcEpisodeList.size(); i++) {
            CdcEpisodeEntity cdcEpisodeEntity = cdcEpisodeList.get(i);
            if (cdcEpisodeEntity.getAdmLocDesc().matches(".*ICU.*")){
                directTime= DateUtil.format(cdcEpisodeEntity.getAdmDate() , "yyyy-MM-dd HH:mm:ss");
                break;
            }
        }
        // 转入ICU
        Wrapper<CdcTransferEntity> transferWrapper = new EntityWrapper<>();
        transferWrapper.eq("episode_id", episodeId).eq("is_active", 1).orderBy("tran_date",true);
        List<CdcTransferEntity> transeferList = cdcTransferService.selectList(transferWrapper);

        for (int i = 0; i < transeferList.size(); i++) {
            CdcTransferEntity cdcTransferEntity=transeferList.get(i);
            //科室病区
            CdcLocationEntity locationEntity = cdcLocationService.selectById(cdcTransferEntity.getTranLocId());
            if (locationEntity.getDescription().matches(".*ICU.*")) {
                transTime = DateUtil.format(cdcTransferEntity.getTranDate(), "yyyy-MM-dd HH:mm:ss");
                break;
            }
        }
        if (!directTime.equals("")){
            return directTime;
        }else if (!transTime.equals("")){
            return transTime;
        }else {
            return "";
        }


    }


    /**
     * 常用短语
     * 获取住院日平均值
     *
     * @param episodeId
     * @param param
     * @param resultType
     * @return
     */
    public Object AverageHospDays(Long episodeId, String param, String resultType) {
        Object resultVal = "";
        Long entityId = sdsQcincaseService.getEntityIdByEpisodeId(episodeId);
        List<SdsQcincaseDataEntity> list = sdsQcincaseDataService.selectDaysByEntityId(entityId);
        int sumDays = list.stream().map(e -> e.getHospDays()).reduce(Integer::sum).get();
        resultVal = StrUtil.deciFormatU(sumDays, list.size());
        return resultVal;
    }

    /**
     * 常用短语
     * 获取住院日中位数
     *
     * @param episodeId
     * @param param
     * @param resultType
     * @return
     */
    public Object MedianHospDays(Long episodeId, String param, String resultType) {
        Object resultVal = "";
        Long entityId = sdsQcincaseService.getEntityIdByEpisodeId(episodeId);
        List<SdsQcincaseDataEntity> list = sdsQcincaseDataService.selectDaysByEntityId(entityId);
        List<Integer> days = new ArrayList<>();
        for (SdsQcincaseDataEntity sdsQcincaseDataEntity : list) {
            days.add(sdsQcincaseDataEntity.getHospDays());
        }
        resultVal = medianInteger(days);
        return resultVal;
    }

    /**
     * 常用短语
     * 获取住院日百分位数
     *
     * @param episodeId
     * @param param
     * @param resultType
     * @return
     */
    public Object PercentileHospDays(Long episodeId, String param, String resultType) {
        Object resultVal = "";
        Long entityId = sdsQcincaseService.getEntityIdByEpisodeId(episodeId);
        List<SdsQcincaseDataEntity> list = sdsQcincaseDataService.selectDaysByEntityId(entityId);
        List<Integer> days = new ArrayList<>();
        for (SdsQcincaseDataEntity sdsQcincaseDataEntity : list) {
            days.add(sdsQcincaseDataEntity.getHospDays());
        }
        resultVal = PercentileInteger(days, param);
        return resultVal;
    }

    /**
     * 常用短语
     * 获取住院费用平均值
     *
     * @param episodeId
     * @param param
     * @param resultType
     * @return
     */
    public Object AverageHospCost(Long episodeId, String param, String resultType) {
        Object resultVal = "";
        Long entityId = sdsQcincaseService.getEntityIdByEpisodeId(episodeId);
        List<SdsQcincaseDataEntity> list = sdsQcincaseDataService.selectDaysByEntityId(entityId);
        BigDecimal sumCost = list.stream().map(e -> e.getHospCost()).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal size = new BigDecimal(list.size());
        resultVal = sumCost.divide(size, 2, BigDecimal.ROUND_HALF_UP);
        return resultVal;
    }

    /**
     * 常用短语
     * 获取住院费用中位数
     *
     * @param episodeId
     * @param param
     * @param resultType
     * @return
     */
    public Object MedianHospCost(Long episodeId, String param, String resultType) {
        Object resultVal = "";
        Long entityId = sdsQcincaseService.getEntityIdByEpisodeId(episodeId);
        List<SdsQcincaseDataEntity> list = sdsQcincaseDataService.selectDaysByEntityId(entityId);
        List<BigDecimal> cost = new ArrayList<>();
        for (SdsQcincaseDataEntity sdsQcincaseDataEntity : list) {
            cost.add(sdsQcincaseDataEntity.getHospCost());
        }
        resultVal = medianBigDecimal(cost);
        return resultVal;
    }


    /**
     * 常用短语
     * 获取住院费用百分位数
     *
     * @param episodeId
     * @param param
     * @param resultType
     * @return
     */
    public Object PercentileHospCost(Long episodeId, String param, String resultType) {
        Object resultVal = "";
        Long entityId = sdsQcincaseService.getEntityIdByEpisodeId(episodeId);
        List<SdsQcincaseDataEntity> list = sdsQcincaseDataService.selectDaysByEntityId(entityId);
        List<BigDecimal> cost = new ArrayList<>();
        for (SdsQcincaseDataEntity sdsQcincaseDataEntity : list) {
            cost.add(sdsQcincaseDataEntity.getHospCost());
        }
        resultVal = PercentileBigDecimal(cost, param);
        return resultVal;
    }

    /**
     * 禁忌症
     * 获取结果
     * 有值返回1，否则返回0
     *
     * @param episodeId
     * @param param
     * @param resultType
     * @return
     */
    public Object ContraindicationInfo(Long episodeId, String param, String resultType) {
        int res = 0;
        //根据禁忌症代码查询禁忌症
        ContraindicationEntity contraindicationEntity = baseContraindicationService.selectOne(new EntityWrapper<ContraindicationEntity>()
                .eq("code", param)
                .eq("active", 1));
        if (StringUtils.isEmpty(contraindicationEntity)) {
            return res;
        } else {
            SdcBusiContraindicationEntity sdcBusiContraindicationEntity = sdcBusiContraindicationService.selectOne(new EntityWrapper<SdcBusiContraindicationEntity>()
                    .eq("episode_id", episodeId)
                    .eq("contraindication_id", contraindicationEntity.getId()));
            if (StringUtils.isEmpty(sdcBusiContraindicationEntity)) {
                return res;
            } else {
                return sdcBusiContraindicationEntity.getResult();
            }
        }

    }


    private double medianInteger(List<Integer> list) {
        double res = 0;
        Collections.sort(list);
        int size = list.size();
        if (size % 2 != 1) {
            res = (list.get(size / 2 - 1) + list.get(size / 2) + 0.0) / 2;//加0.0是为了计算是将int类型转换为浮点型
        } else {
            res = list.get((size - 1) / 2);
        }

        return res;
    }

    private BigDecimal medianBigDecimal(List<BigDecimal> list) {
        if (null == list) {
            return null;
        } else {
            Collections.sort(list);
            int size = list.size();
            if (size % 2 == 1) {
                return list.get((size - 1) / 2);
            } else {
                return (list.get(size / 2 - 1).add(list.get(size / 2))).divide(new BigDecimal(2), 3);
            }
        }

    }


    private Object PercentileInteger(List<Integer> list, String param) {
        Integer[] data = list.toArray(new Integer[list.size()]);
        Arrays.sort(data);
        int p = Integer.valueOf(param);
        int n = data.length;
        //计算指数i=np%
        if ((n * p) % 100 == 0) {
            //若i是整数，则第p百分位数是第i项与第(i+l)项数据的平均值。
            int i = ((n * p) / 100) - 1;
            DecimalFormat df = new DecimalFormat("0.00");
            int sum = data[i] + data[i + 1];
            String s = df.format((float) sum / 2);
            return s;
        } else {
            //若 i 不是整数，将 i 向上取整。大于i的毗邻整数即为第p百分位数的位置
            int i = (int) Math.ceil((n * p * 1.0) / 100);
            return data[i - 1];
        }

    }


    private Object PercentileBigDecimal(List<BigDecimal> list, String param) {
        Collections.sort(list);
        int p = Integer.valueOf(param);
        int n = list.size();
        //计算指数i=np%
        if ((n * p) % 100 == 0) {
            //若i是整数，则第p百分位数是第i项与第(i+l)项数据的平均值。
            int i = ((n * p) / 100) - 1;
            BigDecimal sum = list.get(i).add(list.get(i + 1));
            BigDecimal res = sum.divide(new BigDecimal(2), 2, BigDecimal.ROUND_HALF_UP);
            return res;
        } else {
            //若 i 不是整数，将 i 向上取整。大于i的毗邻整数即为第p百分位数的位置
            int i = (int) Math.ceil((n * p * 1.0) / 100);
            return list.get(i - 1);
        }

    }

    private Map<String, String> handleRegexp(String[] split, String replaceTarget) {
        Map<String, String> res = new HashMap<>();
        //排除sql
        String filterTxt = "";
        //同时满足sql
        String keywordAndTxt = "";
        //满足一个sql
        String keywordOrTxt = "";
        for (String s1 : split) {
            if (s1.contains("!")) {
                filterTxt = filterTxt + "|" + s1.substring(1);
            } else if (s1.contains("&")) {
                //同时满足
                String[] split1 = s1.split("&");
                for (int i = 0, l = split1.length-1; i <= l; i++) {
                    if (i == 0) {
                        keywordAndTxt = keywordAndTxt + " or ( "+replaceTarget+" like '%" + split1[0] + "%'";
                    } else if (i == l) {
                        keywordAndTxt = keywordAndTxt + " and "+replaceTarget+" like '%" + split1[i] + "%')";
                    } else {
                        keywordAndTxt = keywordAndTxt + " and "+replaceTarget+" like '%" + split1[i] + "%'";
                    }
                }
            } else {
                keywordOrTxt = keywordOrTxt + " or ( "+replaceTarget+" like '%" + s1 + "%')";
            }
        }
        keywordOrTxt = keywordOrTxt + keywordAndTxt;

        if (!"".equals(filterTxt)) {
            filterTxt = filterTxt.substring(1);
        }
        if (!"".equals(keywordOrTxt)) {
            keywordOrTxt = keywordOrTxt.replaceFirst("or", "");
        }

        res.put("keywordOrTxt",keywordOrTxt);
        res.put("filterTxt",filterTxt);
        return res;
    }

    private List<Long> handleRisInfo(String paramStr){
        List<Long> ordMastList = new ArrayList<>();
        if (CommonUtil.isNotEmpty(paramStr)){
            paramStr.replace("，", ",");
            //如果参数不为空，通过描述匹配标准化项目查找关联医嘱项
            String[] paramArr = paramStr.split(",");
            Wrapper<SdsStandDicEntity> dicWpr = new EntityWrapper<>();
            //Wrapper<SdsStandDicsubEntity> wpr = new EntityWrapper<>();
            Map<String, String> sqlStrMap = this.handleRegexp(paramArr,"dic_cat_desc");
            String includeStr = sqlStrMap.get("keywordOrTxt");
            String filterStr = sqlStrMap.get("filterTxt");
            dicWpr.where("1=1");
            if (CommonUtil.isNotEmpty(includeStr)) {
                dicWpr.andNew(includeStr);
            }
            if (CommonUtil.isNotEmpty(filterStr)) {
                dicWpr.andNew("dic_cat_desc not regexp {0}",filterStr);
            }
            List<SdsStandDicEntity> dicList = sdsStandDicMapper.selectList(dicWpr);
            //目前只处理标准字典
            if (!dicList.isEmpty()) {
                Map map = new HashMap();
                for (SdsStandDicEntity dicEntity : dicList) {
                    // 查询标准项所有关联医嘱
                    map.put("dicId", dicEntity.getId());
                    //检查医嘱id
                    ordMastList.addAll(sdsFunctionMapper.getRisLinkOrdMthId(map));
                }
            }
            if (ordMastList.isEmpty()) {
                // 如果标准项和子项未找到关联医嘱，直接模糊匹配医嘱项
                sqlStrMap = this.handleRegexp(paramArr,"description");
                includeStr = sqlStrMap.get("keywordOrTxt");
                filterStr = sqlStrMap.get("filterTxt");
                ordMastList.addAll(sdsFunctionMapper.getOrdMastByKeyword(includeStr, filterStr));
            }
        }
        return ordMastList;
    }
}



